package fr.utbm.tx52.stamp.ui.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import fr.utbm.tx52.stamp.R;
import fr.utbm.tx52.stamp.logic.Contact;
import fr.utbm.tx52.stamp.logic.reception.MessageType;
import fr.utbm.tx52.stamp.logic.reception.PullService;
import fr.utbm.tx52.stamp.logic.utils.FileUtil;
import fr.utbm.tx52.stamp.logic.utils.LocalizationUtil;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Share extends Activity
{

	private Uri imageUri;
	private boolean locationState = true;
	private boolean gps = false;
	private LocationManager locationManager;
	private String soundPath;
	private String imagePath;
	private boolean isGpsTagged;
	private Location location;

	public enum RecordState
	{

		NONE,
		RECORDING,
		RECORDED,
		PLAYING,
		PAUSED,
		REPLAY;

		public RecordState next()
		{
			switch (this)
			{
				case PAUSED:
				case REPLAY:
					return PLAYING;
			}
			return RecordState.values()[ordinal() + 1];
		}
	}
	private RecordState recordState = RecordState.NONE;
	/**
	 * Enregistreur audio
	 */
	private MediaRecorder recorder;
	/**
	 * Lecteur audio
	 */
	private MediaPlayer mediaPlayer = new MediaPlayer();

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);
		setTitle(R.string.share);
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		ImageView imageView = (ImageView) findViewById(R.id.share_preview);
		imageUri = null;
		if (getIntent().getData() != null)
		{
			imageUri = getIntent().getData();
		}
		else
		{
			imageUri = getIntent().getExtras().getParcelable(Intent.EXTRA_STREAM);
		}
		String[] filePathColumn =
		{
			MediaStore.Images.Media.DATA
		};
		Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
		cursor.moveToFirst();
		imagePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
		cursor.close();


		imageView.setImageBitmap(FileUtil.loadBitmap(getContentResolver(), imageUri));

		locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		locationManager.addGpsStatusListener(new GpsStatus.Listener()
		{

			public void onGpsStatusChanged(int event)
			{

				gps = locationManager.getGpsStatus(null).getSatellites().iterator().hasNext();
				switch (event)
				{
					case GpsStatus.GPS_EVENT_STARTED:
						gps = true;
						break;
					case GpsStatus.GPS_EVENT_STOPPED:
						gps = false;
						break;
				}
			}
		});

		final LocationListener locationListener = new LocationListener()
		{

			public void onLocationChanged(Location location)
			{
				Share.this.location = location;
			}

			public void onStatusChanged(String provider, int status, Bundle extras)
			{
			}

			public void onProviderEnabled(String provider)
			{
			}

			public void onProviderDisabled(String provider)
			{
			}
		};


		isGpsTagged = LocalizationUtil.coordinateExists(new File(imagePath));

		ImageButton locate = (ImageButton) findViewById(R.id.share_location_toogle);
		locate.setImageResource(isGpsTagged ? R.drawable.ic_menu_dark_location : R.drawable.ic_menu_dark_location_muted);

		locationState = isGpsTagged;
		if (locationState)
		{
			location = new Location("");
			location.setLatitude(LocalizationUtil.getLatitude(new File(imagePath)));
			location.setLongitude(LocalizationUtil.getLongitude(new File(imagePath)));
		}

		locate.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				locationState = !locationState;
				((ImageButton) v).setImageResource(locationState ? R.drawable.ic_menu_dark_location : R.drawable.ic_menu_dark_location_muted);
				if (!isGpsTagged)
				{
					locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
				}

			}
		});

		soundPath = FileUtil.getSoundPath(imagePath);

		recorder = new MediaRecorder();

		ImageButton mic = (ImageButton) findViewById(R.id.share_audio_comment);
		mic.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(final View v)
			{
				switch (recordState)
				{
					case NONE:
						recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
						recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
						recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
						recorder.setOutputFile(soundPath);
						try
						{
							recorder.prepare();
						}
						catch (IllegalStateException e)
						{
							Log.e(Share.class.getSimpleName(), "", e);
						}
						catch (IOException e)
						{
							Log.e(Share.class.getSimpleName(), "", e);
						}
						recorder.start();
						Toast.makeText(Share.this, R.string.recording, Toast.LENGTH_SHORT).show();
						((ImageButton) v).setBackgroundColor(Color.parseColor("#CC0000"));
						break;
					case RECORDING:
						((ImageButton) v).setBackgroundDrawable(null);
						((ImageButton) v).setImageResource(R.drawable.ic_menu_dark_play);
						recorder.stop();
						recorder.reset();
						Toast.makeText(Share.this, R.string.endrecording, Toast.LENGTH_SHORT).show();
						break;
					case RECORDED:
						try
						{
							mediaPlayer.setDataSource(soundPath);
							mediaPlayer.prepare();
							mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
							{

								public void onCompletion(MediaPlayer mp)
								{
									((ImageButton) v).setImageResource(R.drawable.ic_menu_dark_replay);
									recordState = RecordState.REPLAY;
								}
							});

						}
						catch (IOException ex)
						{
							Log.e(Share.class.getSimpleName(), "", ex);
						}
						catch (IllegalArgumentException ex)
						{
							Log.e(Share.class.getSimpleName(), "", ex);
						}
						catch (SecurityException ex)
						{
							Log.e(Share.class.getSimpleName(), "", ex);
						}
						catch (IllegalStateException ex)
						{
							Log.e(Share.class.getSimpleName(), "", ex);
						}
						Toast.makeText(Share.this, R.string.restartrecording, Toast.LENGTH_LONG).show();
					case PAUSED:
					case REPLAY:
						mediaPlayer.start();
						((ImageButton) v).setImageResource(R.drawable.ic_menu_dark_pause);
						break;
					case PLAYING:
						mediaPlayer.stop();
						((ImageButton) v).setImageResource(R.drawable.ic_menu_dark_play);
						break;

				}
				recordState = recordState.next();
			}
		});

		mic.setOnLongClickListener(new View.OnLongClickListener()
		{

			public boolean onLongClick(View v)
			{
				if (recordState.ordinal() >= RecordState.RECORDED.ordinal())
				{
					((ImageButton) v).setImageResource(R.drawable.ic_menu_dark_device_access_mic);
					recordState = RecordState.NONE;
					mediaPlayer.stop();
					mediaPlayer.reset();
					Toast.makeText(Share.this, R.string.deleterecord, Toast.LENGTH_SHORT).show();
					File soundFile = new File(soundPath);
					soundFile.delete();
				}
				return true;
			}
		});

		ImageButton to = (ImageButton) findViewById(R.id.share_to);
		to.setOnClickListener(new View.OnClickListener()
		{

			public void onClick(View v)
			{
				final Intent intent = new Intent(Share.this, ContactPicker.class);
				startActivity(intent);
			}
		});
	}

	/*
	 * @Override
	 */
	public void onReceive(Context context, Intent intent)
	{
		Intent intent_ = new Intent(context, Share.class);
		startActivity(intent_);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.share, menu);

		menu.findItem(R.id.share_send).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
		{

			public boolean onMenuItemClick(MenuItem item)
			{

				if (ContactPicker.selection == null || ContactPicker.selection.isEmpty())
				{
					AlertDialog.Builder builder = new AlertDialog.Builder(Share.this);
					builder.setMessage(R.string.add_contact).setCancelable(false).setPositiveButton(R.string.ok,
						new DialogInterface.OnClickListener()
						{

							public void onClick(DialogInterface dialog,
								int id)
							{
							}
						});
					builder.create().show();
					return true;
				}

				if (location != null)
				{
					LocalizationUtil.writeLocation(location, new File(imagePath));
				}

				// envoi photo
				PullService.getInstance().sendFile(imagePath, MessageType.FILE_IMAGE);

				// envoi commentaire �crit
				EditText et = (EditText) findViewById(R.id.share_comment);
				PullService.getInstance().sendMessage(MessageType.COMMENT, et.getText().toString());

				// envoi commentaire audio
				if (recordState.ordinal() >= RecordState.RECORDED.ordinal())
				{
					PullService.getInstance().sendFile(soundPath, MessageType.FILE_SOUND);
				}

				List<String> phoneList = new ArrayList<String>();
				for (Contact contact : ContactPicker.selection)
				{
					phoneList.add(contact.getPhoneNumber());
				}

				// enfin l'envoi du message est comme un commit, il signale que l'on a tout envoy� ce qu'on voulait
				PullService.getInstance().sendMessage(MessageType.SHARE_PHOTO, phoneList);

				finish();
				return false;
			}
		});

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				if (!Main.launched)
				{
					final Intent intent = new Intent(this, Main.class);
					startActivity(intent);
				}
				finish();
				return true;
		}
		return false;
	}
}
